import { defineStore } from 'pinia';
import { showToast } from '@/utils/toast';

// 角色管理状态仓库
export const useRoleStore = defineStore('role', {
  state: () => ({
    // 角色列表
    roles: [],
    // 角色权限映射
    rolePermissions: {},
    // 加载状态
    loading: {
      roles: false,
      permissions: false,
      submit: false
    },
    // 分页信息
    pagination: {
      page: 1,
      pageSize: 10,
      total: 0
    },
    // 筛选条件
    filters: {
      keyword: '',
      status: ''
    },
    // 缓存的角色数据
    cachedRoles: {}
  }),

  getters: {
    // 获取角色数量
    roleCount: (state) => state.roles.length,
    
    // 根据ID获取角色
    getRoleById: (state) => (id) => {
      return state.roles.find(role => role.id === id) || null;
    },
    
    // 获取活跃角色数量
    activeRoleCount: (state) => {
      return state.roles.filter(role => role.status === 'active').length;
    },
    
    // 获取角色及其权限信息
    getRolesWithPermissions: (state) => {
      return state.roles.map(role => ({
        ...role,
        permissions: state.rolePermissions[role.id] || []
      }));
    },
    
    // 根据权限ID获取拥有该权限的角色
    getRolesByPermissionId: (state) => (permissionId) => {
      return state.roles.filter(role => {
        const permissions = state.rolePermissions[role.id] || [];
        return permissions.some(p => p.id === permissionId);
      });
    }
  },

  actions: {
    /**
     * 获取角色列表
     */
    async getRoles() {
      try {
        this.loading.roles = true;
        const response = await requestInstance.get('roles', {
          params: {
            page: this.pagination.page,
            pageSize: this.pagination.pageSize,
            keyword: this.filters.keyword,
            status: this.filters.status
          }
        });
        
        this.roles = response.data.roles || [];
        this.pagination.total = response.data.total || 0;
        
        // 更新缓存
        this.roles.forEach(role => {
          this.cachedRoles[role.id] = role;
        });
        
        return this.roles;
      } catch (error) {
        console.error('获取角色列表失败:', error);
        showToast('获取角色列表失败', 'error');
        return [];
      } finally {
        this.loading.roles = false;
      }
    },
    
    /**
     * 获取所有角色（不分页）
     */
    async getAllRoles() {
      try {
        this.loading.roles = true;
        const response = await requestInstance.get('roles/all', {
          params: {
            status: this.filters.status
          }
        });
        
        this.roles = response.data || [];
        
        // 更新缓存
        this.roles.forEach(role => {
          this.cachedRoles[role.id] = role;
        });
        
        return this.roles;
      } catch (error) {
        console.error('获取所有角色失败:', error);
        showToast('获取所有角色失败', 'error');
        return [];
      } finally {
        this.loading.roles = false;
      }
    },
    
    /**
     * 获取角色详情
     * @param {string|number} id - 角色ID
     */
    async getRoleDetail(id) {
      try {
        // 先检查缓存
        if (this.cachedRoles[id]) {
          return this.cachedRoles[id];
        }
        
        this.loading.submit = true;
        const response = await requestInstance.get(`/api/roles/${id}`);
        const role = response.data;
        
        // 更新缓存
        this.cachedRoles[id] = role;
        
        // 更新角色列表中的对应项
        const index = this.roles.findIndex(r => r.id === id);
        if (index !== -1) {
          this.roles[index] = role;
        }
        
        return role;
      } catch (error) {
        console.error(`获取角色${id}详情失败:`, error);
        showToast('获取角色详情失败', 'error');
        return null;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 获取角色权限
     * @param {string|number} roleId - 角色ID
     */
    async getRolePermissions(roleId) {
      try {
        this.loading.permissions = true;
        const response = await requestInstance.get(`/api/roles/${roleId}/permissions`);
        const permissions = response.data || [];
        
        // 存储角色权限映射
        this.rolePermissions[roleId] = permissions;
        
        return permissions;
      } catch (error) {
        console.error(`获取角色${roleId}权限失败:`, error);
        showToast('获取角色权限失败', 'error');
        return [];
      } finally {
        this.loading.permissions = false;
      }
    },
    
    /**
     * 批量获取多个角色的权限
     * @param {Array} roleIds - 角色ID数组
     */
    async getRolesPermissions(roleIds) {
      try {
        this.loading.permissions = true;
        const response = await requestInstance.get('roles/permissions', {
          params: {
            roleIds: roleIds.join(',')
          }
        });
        
        // 更新角色权限映射
        if (response.data && typeof response.data === 'object') {
          Object.keys(response.data).forEach(roleId => {
            this.rolePermissions[roleId] = response.data[roleId] || [];
          });
        }
        
        return response.data;
      } catch (error) {
        console.error('批量获取角色权限失败:', error);
        showToast('批量获取角色权限失败', 'error');
        return {};
      } finally {
        this.loading.permissions = false;
      }
    },
    
    /**
     * 创建角色
     * @param {Object} role - 角色数据
     */
    async createRole(role) {
      try {
        this.loading.submit = true;
        const response = await requestInstance.post('roles', role);
        const newRole = response.data;
        
        // 更新本地状态
        this.roles.unshift(newRole);
        this.pagination.total++;
        
        // 更新缓存
        this.cachedRoles[newRole.id] = newRole;
        
        showToast('角色创建成功', 'success');
        return newRole;
      } catch (error) {
        console.error('创建角色失败:', error);
        showToast(error.response?.data?.message || '创建角色失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 更新角色
     * @param {string|number} id - 角色ID
     * @param {Object} role - 角色数据
     */
    async updateRole(id, role) {
      try {
        this.loading.submit = true;
        const response = await requestInstance.put(`/api/roles/${id}`, role);
        const updatedRole = response.data;
        
        // 更新本地状态
        const index = this.roles.findIndex(r => r.id === id);
        if (index !== -1) {
          this.roles[index] = updatedRole;
        }
        
        // 更新缓存
        this.cachedRoles[id] = updatedRole;
        
        showToast('角色更新成功', 'success');
        return updatedRole;
      } catch (error) {
        console.error(`更新角色${id}失败:`, error);
        showToast(error.response?.data?.message || '更新角色失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 删除角色
     * @param {string|number} id - 角色ID
     */
    async deleteRole(id) {
      try {
        this.loading.submit = true;
        await requestInstance.delete(`/api/roles/${id}`);
        
        // 更新本地状态
        this.roles = this.roles.filter(role => role.id !== id);
        this.pagination.total--;
        
        // 移除缓存
        delete this.cachedRoles[id];
        delete this.rolePermissions[id];
        
        showToast('角色删除成功', 'success');
        return true;
      } catch (error) {
        console.error(`删除角色${id}失败:`, error);
        showToast(error.response?.data?.message || '删除角色失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 批量删除角色
     * @param {Array} ids - 角色ID数组
     */
    async batchDeleteRoles(ids) {
      try {
        this.loading.submit = true;
        await requestInstance.post('roles/batch-delete', { ids });
        
        // 更新本地状态
        this.roles = this.roles.filter(role => !ids.includes(role.id));
        this.pagination.total -= ids.length;
        
        // 移除缓存
        ids.forEach(id => {
          delete this.cachedRoles[id];
          delete this.rolePermissions[id];
        });
        
        showToast(`成功删除${ids.length}个角色`, 'success');
        return true;
      } catch (error) {
        console.error('批量删除角色失败:', error);
        showToast(error.response?.data?.message || '批量删除角色失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 切换角色状态（启用/禁用）
     * @param {string|number} id - 角色ID
     * @param {boolean} active - 是否启用
     */
    async toggleRoleStatus(id, active) {
      try {
        this.loading.submit = true;
        const response = await requestInstance.put(`/api/roles/${id}/status`, { status: active ? 'active' : 'inactive' });
        const updatedRole = response.data;
        
        // 更新本地状态
        const index = this.roles.findIndex(role => role.id === id);
        if (index !== -1) {
          this.roles[index] = updatedRole;
        }
        
        // 更新缓存
        this.cachedRoles[id] = updatedRole;
        
        showToast(`角色${active ? '启用' : '禁用'}成功`, 'success');
        return updatedRole;
      } catch (error) {
        console.error(`切换角色${id}状态失败:`, error);
        showToast(error.response?.data?.message || '切换角色状态失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 分配角色权限
     * @param {string|number} roleId - 角色ID
     * @param {Array} permissionIds - 权限ID数组
     */
    async assignRolePermissions(roleId, permissionIds) {
      try {
        this.loading.submit = true;
        const response = await requestInstance.put(`/api/roles/${roleId}/permissions`, {
          permissionIds
        });
        
        // 更新角色权限映射
        this.rolePermissions[roleId] = response.data || [];
        
        showToast('角色权限分配成功', 'success');
        return true;
      } catch (error) {
        console.error(`分配角色${roleId}权限失败:`, error);
        showToast(error.response?.data?.message || '角色权限分配失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 批量更新角色状态
     * @param {Array} ids - 角色ID数组
     * @param {string} status - 状态值
     */
    async batchUpdateRoleStatus(ids, status) {
      try {
        this.loading.submit = true;
        await requestInstance.post('roles/batch-status', { ids, status });
        
        // 更新本地状态
        this.roles = this.roles.map(role => {
          if (ids.includes(role.id)) {
            const updatedRole = { ...role, status };
            // 更新缓存
            this.cachedRoles[role.id] = updatedRole;
            return updatedRole;
          }
          return role;
        });
        
        showToast(`成功更新${ids.length}个角色状态`, 'success');
        return true;
      } catch (error) {
        console.error('批量更新角色状态失败:', error);
        showToast(error.response?.data?.message || '批量更新角色状态失败', 'error');
        throw error;
      } finally {
        this.loading.submit = false;
      }
    },
    
    /**
     * 搜索角色
     * @param {string} keyword - 搜索关键词
     */
    searchRoles(keyword) {
      this.filters.keyword = keyword;
      this.pagination.page = 1;
      this.getRoles();
    },
    
    /**
     * 筛选角色状态
     * @param {string} status - 状态值
     */
    filterRolesByStatus(status) {
      this.filters.status = status;
      this.pagination.page = 1;
      this.getRoles();
    },
    
    /**
     * 更新分页信息
     * @param {Object} pagination - 分页信息
     */
    updatePagination(pagination) {
      this.pagination = { ...this.pagination, ...pagination };
      this.getRoles();
    },
    
    /**
     * 清空筛选条件
     */
    resetFilters() {
      this.filters = {
        keyword: '',
        status: ''
      };
      this.pagination.page = 1;
      this.getRoles();
    },
    
    /**
     * 清空缓存
     */
    clearCache() {
      this.cachedRoles = {};
      this.rolePermissions = {};
    },
    
    /**
     * 刷新角色列表
     */
    refreshRoles() {
      this.clearCache();
      this.getRoles();
    }
  }
});